# !/usr/bin/python
# -*- coding: UTF-8 -*-
# sudo pip install pypdf
# sudo pip install reportlab
# sudo pip install PyPDF2

import os 
import sys
import Image
import re
from PyPDF2 import PdfFileMerger
from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.platypus import PageBreak
from reportlab.lib.pagesizes import A4,landscape
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.lib.styles import ParagraphStyle as PS
from reportlab.platypus.paragraph import Paragraph
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.platypus.frames import Frame
from reportlab.lib.units import cm

class searchfile():
    def __init__(self):
        self.namelist = []
        
    def search(self,path, con):
        for filename in os.listdir(path):
            fp = os.path.join(path, filename)
            if os.path.isfile(fp) and re.match(con,os.path.basename(fp)): 
                self.namelist.append(fp)
            elif os.path.isdir(fp):
                self.search(fp, con)
        return self.namelist; 

def convert_to_pdf(filename):
    im = Image.open(filename)
    im_w,im_h = im.size
    newname = filename[:filename.rindex('.')]+'.pdf'
    c = canvas.Canvas(newname,pagesize = (im_w,im_h))
    c.drawImage(filename,0,0,im_w,im_h)
#    c.drawString(0,0,"HelloWorld!")
    c.save()
    c.showPage()
    print "convert finish:",filename,'to',newname
    
    return;

def mergepdf(filenamelist,outputfilename):
    fn = []
    merger = PdfFileMerger()
    for filename in filenamelist:
        fn.append(open(filename, "rb"))
    for inf in fn:
        merger.append(inf)
    output = open(outputfilename, "wb")
    merger.write(output)
    return;
    
def printusage():
    print "Usage:"
    print "     python mkpdf.py [-h help] [-c convert img file to pdf] [-d convert dir Matching condition] [-m merge pdf dir Matching condition] "
    print "     python mkpdf.py -d ./ '^00_0b.*?[^data].jpg$' "
    return;
    
if __name__ == '__main__':
    if '-h' in sys.argv:
        printusage()
    elif '-c' in sys.argv:
        convert_to_pdf(sys.argv[sys.argv.index("-c") + 1])
    elif '-d' in sys.argv:
        filelist = searchfile().search(sys.argv[2],sys.argv[3])
        for filename in filelist:
            convert_to_pdf(filename)
    elif '-m' in sys.argv:
        filelist = searchfile().search(sys.argv[2],sys.argv[3])
        mergepdf(filelist,'output_merge.pdf')
    elif '-s' in sys.argv:
        filelist = searchfile().search(sys.argv[2],sys.argv[3])
#        print filelist  
        mergepdf(filelist,'output_report.pdf')



